//app.js

var lajax = require('./common/lajax4wx.js');
var common = require('./common/common.js')
var ConstantData = require('./common/constant_data.js')
var util = require('./utils/util.js');
var aesUtil = require("./utils/aes.js");
var commonUtil = require('./utils/commonUtil');

//陪护椅相关参数名
function e(e, a, o) {
  return a in e ? Object.defineProperty(e, a, {
    value: o,
    enumerable: !0,
    configurable: !0,
    writable: !0
  }) : e[a] = o, e;
}
var a;

App({
  lajax: null,
  BASE_URL: ConstantData.CONSTATNT_DATA.BASE_URL,
  DEVICE_QRCODE_URL_PREFIX: ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX,
  TIME_CARD_QRCODE_URL_PREFIX: ConstantData.CONSTATNT_DATA.TIME_CARD_QRCODE_URL_PREFIX,
  TIME_CARD_OUTPATIENT_QRCODE_URL_PREFIX: ConstantData.CONSTATNT_DATA.TIME_CARD_OUTPATIENT_QRCODE_URL_PREFIX,
  TIME_CARD_NO_PAY: -103,
  businessName: {},
  login_info: {
    stat: 0,
    pass: '',
    temp: '',
    ltime: ''
  },

  onError: function (err) {
    console.log('上报错误！', err);
    this.globalData.onErrorTimes--;
    if (this.globalData.onErrorTimes < 0) {
      return
    }

    let systemInfo = wx.getStorageSync('systeminfo');
    let nowTime = util.formatTime(new Date()) + '-----';
    var miniVer = ConstantData.CONSTATNT_DATA.MINI_VERSION;
    console.log('onErrorTimes', this.globalData.onErrorTimes);
    wx.request({
      url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/error/bc',
      header: this.getHeader(),
      data: {
        homingPileBlueName: 'onError', //归位桩的蓝牙名称,最长100个字
        phoneOs: systemInfo.system, //手机系统信息,最长245
        phoneFactory: systemInfo.model, //手机厂商,最长245
        phoneType: systemInfo.model || systemInfo.brand, //手机型号,最长245
        weixinVer: systemInfo.version + ',' + systemInfo.SDKVersion + ',' + miniVer, //微信版本号,最长45
        errType: parseInt(ConstantData.err_type.onerror.replace(/[^0-9]/ig, '')), //错误类型,最大值127；1.搜索,2.连接,3.auth,4.init 5. 95 6. 85
        errDesc: nowTime + err, //错误描述,最长545
      },
      success: function (res) {
        console.log("onError上传成功", res)
      },
      fail: function (res) {
        console.log("onError上传失败", res)
      }
    })
  },
  onShow: function (res) {
    this.globalData.appOnShowData = res;
    this.globalData.isAllowBroadcastBack = 1;
  },
  globalData: {
    defCheckAgreeService: true, // 默认是否勾选登录页面的同意服务协议按钮（服务器下发的数据会覆盖该默认设置）
    statusBarHeight: 0,
    navBarHeight: 0,
    isSubOffical: false, //是否关注公众号
    mpWebUrl: 'https://www.ejiakanghu.cn/mini/older-offical?v=1.0&t=' + new Date().getTime(), //公众号关注页面，通过重定向到对应的公众号页面
    miniBeeConfig: null,
    userInfo: null,
    userStay: false,
    isConnecting: false,
    onErrorTimes: 0,
    isDirectConnect: false,
    RSSI: 0,
    //陪护椅蓝牙参数信息
    bleVariable: (a = {
        mMacAddress: "",
        mDrawerMacAddress: "",
        unlockPwd: "",
        drawerUnlockPwd: "",
        cmds: {
          getTokenCmd: [6, 1, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
          queryLockStatusCmd: [5, 14, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
          queryBatteryCmd: [2, 1, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12],
          unlockCmd: [5, 1, 6, 48, 48, 48, 48, 48, 48, 12, 12, 12, 12, 12, 12, 12],
          lockCmd: [5, 12, 1, 1, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12]
        },
        dataPrefix: {
          getTokenPrefix: "6,2",
          queryLockStatusPrefix: "5,15",
          queryLockBatteryPrefix: "2,2",
          unlockPrefix: "5,2",
          lockPrefix: "5,8",
          lockPrefix2: "5,13",
          deviceDisconnectPrefix: "5,23",
          unknowCmdPrefix: "5,3"
        },
        action: {
          actionUnlock: 1,
          actionLock: 2
        },
        errCode: {
          errTokenErr: 1
        },
        errContent: {
          errTokenErrContent: "Token错误"
        },
        currAction: 0,
        akey: [58, 96, 67, 42, 92, 1, 33, 31, 41, 30, 15, 78, 12, 19, 40, 37],
        netWorkAKey: [110, 100, 220, 70, 41, 71, 219, 232, 73, 168, 149, 228, 26, 189, 253, 209]
      }, e(a, "unlockPwd", [48, 48, 48, 48, 48, 48]), e(a, "drawerUnlockPwd", [48, 48, 48, 48, 48, 48]),
      e(a, "aiv", []), e(a, "keyBv", null), e(a, "ivBv", null), e(a, "keyWA", null), e(a, "ivWA", null),
      e(a, "mDeviceId", ""), e(a, "serviceId", "0000FEE7-0000-1000-8000-00805F9B34FB"),
      e(a, "services", []), e(a, "cdRead", "000036F6-0000-1000-8000-00805F9B34FB"), e(a, "cdWrite", "000036F5-0000-1000-8000-00805F9B34FB"),
      e(a, "UUID_SERVER", "0000FEE7-0000-1000-8000-00805F9B34FB"), e(a, "isDeviceFound", !1),
      e(a, "isConnected", !1), e(a, "isCommuOver", !0), e(a, "scanDeviceOverTime", 2e4),
      e(a, "connectDeviceOverTime", 12e3), e(a, "commuDeviceOverTime", 12e3), e(a, "commuDeviceOverTimeRetryCnt", 3),
      e(a, "token", [0, 0, 0, 0]), a),


  },
  onLaunch: function () {

    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        wx.setStorage({
          key: 'systeminfo',
          data: res,
        })
        let custom = wx.getMenuButtonBoundingClientRect()
        that.globalData.statusBarHeight = res.statusBarHeight
        if(custom) {
          that.globalData.navBarHeight = custom.height + (custom.top - res.statusBarHeight) * 2
        }        
      },
    })

    //陪护椅蓝牙相关参数
    that.globalData.bleVariable.keyBv = new Int8Array(that.globalData.bleVariable.akey),
      that.globalData.bleVariable.ivBv = new Int8Array(that.globalData.bleVariable.aiv),
      that.globalData.bleVariable.keyWA = aesUtil.CryptoJS.enc.int8array.parse(that.globalData.bleVariable.keyBv),
      that.globalData.bleVariable.ivWA = aesUtil.CryptoJS.enc.int8array.parse(that.globalData.bleVariable.ivBv);

    that.globalData.loginData = {};
    that.globalData.scan = {
      qrc: ''
    };
    that.globalData.wxScan = {
      qrc: ''
    };
    that.globalData.devConnected = false;
    that.globalData.isOpenLock = false;
    that.globalData.networkIsCon = true;

    wx.removeStorageSync('scan_qrc');
    wx.removeStorageSync('has_opened_gprs');

    const baseVer = wx.getSystemInfoSync().SDKVersion
    commonUtil.getMiniSetting(baseVer)

    this.loginAuth('', '')

    this.lajax = lajax;
    this.lajax.init({
      url: 'https://elog.ejiakanghu.com.cn/api/logger/wechat',
      app: this,
      systemInfo: wx.getSystemInfoSync(),
      miniVer: ConstantData.CONSTATNT_DATA.MINI_VERSION,
      printLogFlg: true, //是否在控制台输入日志，true输出,false不输出
      printBleLog: true,
      printAppLog: true,
      connectInfo: {
        conReqid: 0,
        conBleMac: null,
        conUserId: 0,
      },
    });

  },
  getHeader: function () {
    var that = this;
    let pass = that.getUserLoginPass();
    let temp = that.getUserLoginTemp();
    let ltime = that.getUserLoginTime();
    let ctype = that.getUserLoginCtype();
    var header = {
      'content-type': 'application/x-www-form-urlencoded',
      'stat': '1',
      'pass': pass,
      'temp': temp,
      'ltime': ltime,
      'ctype': ctype,
      'platform': 'wxmini'
    }
    return header;
  },
  handleRes: function (res, that) {
    let app_that = this
    console.log('handleRes-->', res.data);
    if (that && res && res.data) {
      let result = res.data.result
      let description = res.data.description
      app_that.globalData.showMaintDesc = description
      if (result == 'maint') {
        that.setData({
          platformTipDesc: description,
          showMaintPlatform: true,
        })
        app_that.globalData.maintShowFlg = true
        app_that.globalData.showMaintPlatform = true
        return true
      } else if (result == 'wxmini') {
        that.setData({
          platformTipDesc: description,
          showUseOtherMini: true,
        })
        app_that.globalData.maintShowFlg = true
        app_that.globalData.showUseOtherMini = true
        return true
      }
      app_that.globalData.maintShowFlg = false
      app_that.globalData.showMaintPlatform = false
      app_that.globalData.showUseOtherMini = false
      return false
    } else if (res.statusCode == 500) {
      wx.showToast({
        title: '服务' + res.statusCode + '，请稍候再试',
        icon: 'none'
      })
      app_that.globalData.maintShowFlg = true
      return true;
    }
    return false;
  },
  getUserLoginTime: function () {
    return this.globalData.loginData && this.globalData.loginData.ltime ? this.globalData.loginData.ltime : wx.getStorageSync('ltime')
  },
  getUserLoginPass: function () {
    return this.globalData.loginData && this.globalData.loginData.pass ? this.globalData.loginData.pass : wx.getStorageSync('pass');
  },
  getUserLoginTemp: function () {
    return this.globalData.loginData && this.globalData.loginData.temp ? this.globalData.loginData.temp : wx.getStorageSync('temp');
  },
  getUserLoginCtype: function () {
    let wxType = this.globalData.loginData && this.globalData.loginData.wxctype ? this.globalData.loginData.wxctype : wx.getStorageSync('wxctype');
    return wxType ? wxType : 'wxmini';
  },
  getUserLoginNoPhone: function () {
    return this.globalData.loginData && this.globalData.loginData.nophone ? this.globalData.loginData.nophone : wx.getStorageSync('nophone');
  },
  getScanQrcContent: function () {
    return this.globalData.qrc && this.globalData.scan.qrc ? this.globalData.scan.qrc : wx.getStorageSync('scan_qrc');
  },
  clearTimeoutTimer: function () {
    clearTimeout(this.globalData.conTimeoutTimer);
    clearTimeout(this.globalData.data95ReceiveTimer);
    clearTimeout(this.globalData.directConnectTimer);
    clearTimeout(this.globalData.auto95RecTimer);
  },
  /**
   * 发起request请求
   * 如果不存在pass或过期则先登录获取，再进行访问
   */
  executeRequest: function (callBack) {

    var url = ''
    if (callBack) {
      var callBackStr = callBack.toString()
      var re = /\+\s*(\w*\S*)/ig;
      var matches = re.exec(callBackStr);
      if (matches) {
        console.log(matches, '这是matches')
        var urlSplitFirstIndex = matches[0].indexOf("/")
        var urlTemp = matches[0].substring(urlSplitFirstIndex)
        var urlSplitLastIndexA = urlTemp.indexOf("'")
        var urlSplitLastIndexB = urlTemp.indexOf("\"")
        url = urlTemp.substring(0, urlSplitLastIndexA == -1 ? urlSplitLastIndexB : urlSplitLastIndexA)
      }
    }

    var that = this
    var pass = that.getUserLoginPass()
    var timestamp = Date.parse(new Date());

    if (!pass) {
      //不存在登录pass
     let loginNumber=1
     wx.showLoading({
      title: '加载中',
    })
     let passtime= setInterval(() => {
       console.log('轮询pass状态=>>',loginNumber,that.getUserLoginPass())
        pass = that.getUserLoginPass()
        if (!pass) {
          loginNumber=loginNumber+1
          if(loginNumber==6){
            wx.hideLoading()
            clearInterval(passtime)
            wx.showToast({
              title: '加载失败',
              icon: 'error',
              duration: 2000
            })
            console.error("不存在登录pass", url);
            // return 'no_pass'
          }else{
            // this.loginAuth('', '')
          } 
        } else {
          wx.hideLoading()
          clearInterval(passtime)
          var header = that.getHeader()
          callBack(header)   
        }
      }, 500)
      return 'no_pass'
    } else {
      //pass过期
      var ltime = that.getUserLoginTime();
      var diff = timestamp - ltime
      if (diff <= -5000 || diff > 60 * 60 * 1000) {
        console.warn("pass过期", ltime, diff);
        //移除过期的pass
        wx.removeStorageSync('pass')
        // this.loginAuth('','')
      } else {

        var header = that.getHeader()
        callBack(header)
        return

      }

    }
    var getLoginAuthTime = null;
    let times = setInterval(function () {
      if (that.globalData.maintShowFlg) {
        console.log("清空请求超时定时器", times)
        clearInterval(times)
        return
      }
      let storePass = that.getUserLoginPass()
      if (storePass) {
        let header = that.getHeader()
        callBack(header)
        // 这里必须要清除
        clearInterval(times)
        if (getLoginAuthTime) {
          clearTimeout(getLoginAuthTime);
        }
      } else {
        var curTimestamp = Date.parse(new Date())
        var timeout = curTimestamp - timestamp;
        if (getLoginAuthTime == null) {
          getLoginAuthTime = setTimeout(() => {
            that.loginAuth('', '')
          }, 2000);
        }

        if (timeout > 30000) {
          wx.showToast({
            title: '请求超时,请稍后重试',
          })

          common.recordErrorInfo(1010, "getHeaderTimeout:" + url + "," + curTimestamp)

          callBack(header)

          // 这里必须要清除
          clearInterval(times)
        }
      }
    }, 1000)

    return times
  },
  toPay: function (orderCode) {
    console.log("去支付。。。" + orderCode)
    wx.request({
      url: this.BASE_URL + '/ejiam/wxmini/weixin/pay',
      header: this.getHeader(),
      data: {
        orderCode: orderCode
      },
      success: function (res) {
        var data = res.data
        console.log("支付结果---" + data.result)
        if (data.result != 0 || !data.data || !data.data.timeStamp) {
          wx.showToast({
            title: data.description ? data.description : '支付失败'
          })
          return
        }
        wx.requestPayment({
          appId: 'wx0e458dc331e557cc',
          timeStamp: data.data.timeStamp,
          nonceStr: data.data.nonceStr,
          package: data.data.package,
          signType: data.data.signType,
          paySign: data.data.paySign,
          success: function (res) {
            wx.showToast({
              title: 'SUCCESS',
            })
            console.log("SUCCESS")
            console.log(res)
          },
          fail: function (res) {
            wx.showToast({
              title: 'Fail',
            })
            common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? "app1-" + JSON.stringify(res) : '');
          },
          complete: function (res) {
            console.log("complete--" + data.data.paySign)
            console.log(res)
          }
        })
      }
    })
  },
  /**
   * 请求时不存在pass的情况处理
   * @param {} callback 
   */
  reqNoPassHandle(callback, reqRst) {
    console.log("------->reqRst=", reqRst)
    if (reqRst == 'no_pass') {
      callback()
    }
  },
  /**
   * 支付前检验登录openId
   * @param {*} orderCode 
   * @param {*} callBack 
   */
  toPayValideLogin: function (orderCode, callBack) {
    wx.login({
      success(res) {
        if (res.code) {
          callBack(res.code, orderCode, '');
        } else {
          callBack('', orderCode, res.errMsg);
        }
      },
      fail: function (err) {
        callBack('', orderCode, JSON.stringify(err) + "");
      }
    })
  },
  loginAuth: function (phone, pcode) {
    var that = this;
    //调用登录接口
    wx.login({
      success: function (res) {
        console.log('开始登录=>>>>>', res);
        if (res.code) {
          //发起网络请求
          wx.request({
            url: that.BASE_URL + '/lease/auth/login',
            header: that.getHeader(),
            data: {
              code: res.code,
              phone: phone,
              pcode: pcode
            },
            success: function (res) {
              if (!res.statusCode) {
                return;
              }
              let netErr = that.handleRes(res, that.globalData._that);
              if (netErr) {
                return
              }

              var result = res.data.result;
              if (result == 0) {
                try {
                  that.globalData.loginData = res.data.data;
                  wx.setStorageSync('pass', res.data.data.pass);
                  wx.setStorageSync('temp', res.data.data.temp);
                  wx.setStorageSync('ltime', res.data.data.ltime);
                  wx.setStorageSync('cpass', res.data.data.cpass);
                  wx.setStorageSync('uuid', res.data.data.uuid);
                  wx.setStorageSync('nophone', res.data.data.nophone);
                  wx.setStorageSync('isGetUserPhone', res.data.data.adminUserPhone);
                } catch (e) {}
                if (phone) {
                  wx.navigateBack({
                    delta: 2
                  });
                }
              } else {
                if (result == 2) {
                  if (that.globalData._that && that.globalData._that.pageName == 'index') {
                    that.globalData._that.setData({
                      phoneAuthStatus: true,
                      phoneAuthBtt: ''
                    });
                  } else {
                    wx.navigateTo({
                      url: '../login/login',
                    });
                  }
                } else {
                  wx.showToast({
                    title: res.data.description
                  });
                }
              }
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
        // wx.getUserInfo({
        //   success: function (res) {              
        //     that.globalData.userInfo = res.userInfo;
        //     typeof cb == "function" && cb(that.globalData.userInfo)
        //   }
        // })
      }
    });

  },
  sendCustomerMsg: function (msg) {
    var that = this
    wx.request({
      url: this.BASE_URL + '/customer_msg/send',
      header: that.getHeader(),
      data: msg,
      success: function (res) {
        console.log("send customer msg success")
        console.log(res)
      },
      fail: function (res) {
        console.log("send customer msg fail")
        console.log(res)
      }
    })
  },
  /**
   * 扫描包时卡二维码处理
   */
  scanTimeCardQrcodeHandle: function (qrcodeContent) {
    var that = this

    qrcodeContent = decodeURIComponent(qrcodeContent)
    if (qrcodeContent != null && qrcodeContent.indexOf(this.TIME_CARD_QRCODE_URL_PREFIX) == 0) {

      var strLen = this.TIME_CARD_QRCODE_URL_PREFIX.length
      var cardNumber = qrcodeContent.substring(strLen);
      console.log("---->>cardNumber=" + cardNumber)

      that.toTimeCardDetail(cardNumber)
    }
  },
  /**
   * 去包时卡详情页
   */
  toTimeCardDetail: function (cardNumber) {
    wx.reLaunch({
      url: './pkgBak/pages/time_card/detail/time_card_detail?cn=' + cardNumber,
    })
  },
  /**
   * 处理包时卡
   * 支付:弹框输入要绑定的手机号，及相应的备注标签信息
   * 绑定:后台服务绑定完后返回结果
   */
  handleTimeCard: function (cardNumber) {
    var that = this
    //判断参数是否填写
    if (cardNumber == null || cardNumber == '') {
      wx.showToast({
        title: '卡号不能为空!!',
      })
      return;
    }
    wx.request({
      url: that.BASE_URL + '/lease_time_card/bind',
      header: that.getHeader(),
      data: {
        cn: cardNumber
      },
      success: function (res) {
        var rst = res.data.result
        var desc = res.data.description
        if (rst == 0) {
          //移除临时存储的包时卡卡号
          wx.removeStorageSync('time_card_number')
          wx.showToast({
            title: desc,
          })
          //TODO 关闭弹框
        } else {
          //未支付,弹出输入手机号及验证码的框,进行支付
          if (rst == that.TIME_CARD_NO_PAY) {
            that.toTimeCardDetail(cardNumber)
            return
          }

          wx.showToast({
            title: desc,
          })
        }
        console.log("bind card result is:" + desc + "," + rst)
      },
      fail: function (res) {
        wx.showToast({
          title: '请稍后重试',
        })
        console.log("bind card request error")
        console.log(res)
      }
    })
  },
  /**
   * 调用微信支付，去支付包时卡
   */
  toPayTimeCard: function (orderCode) {
    wx.request({
      url: app.BASE_URL + '/ejiam/wxmini/weixin/pay',
      header: app.getHeader(),
      data: {
        orderCode: orderCode
      },
      success: function (res) {
        var data = res.data
        console.log("支付结果---" + data.result)
        if (data.result != 0 || !data.data || !data.data.timeStamp) {
          that.setData({
            alertBoxStatus: true,
            alertBoxTipContent: data.description ? data.description : '支付失败'
          })
          return
        }

        wx.requestPayment({
          appId: 'wx0e458dc331e557cc',
          timeStamp: data.data.timeStamp,
          nonceStr: data.data.nonceStr,
          package: data.data.package,
          signType: data.data.signType,
          paySign: data.data.paySign,
          success: function (res) {
            console.log("SUCCESS")
            console.log(res)
            wx.showToast({
              title: '支付成功',
            })
          },
          fail: function (res) {
            common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'app2-' + JSON.stringify(res) : '');
          },
          complete: function (res) {
            console.log("complete--" + data.data.paySign)
            console.log(res)
          }
        })

      },
      fail: function (res) {
        wx.showToast({
          title: '请稍后重试',
        })
      }
    })
  },
  loginHandle: function (passFlg) {
    try {
      var uuid = wx.getStorageSync('uuid');
      if (uuid) {
        if (passFlg) {
          this.changePass(); //更换令牌     
        }
      } else {
        this.loginAuth('', '')
      }
    } catch (e) {}
  },
  changePass: function () {
    var that = this;
    wx.request({
      url: that.BASE_URL + '/lease/auth/cpass',
      method: 'post',
      header: that.getHeader(),
      data: {
        cpass: wx.getStorageSync('cpass'),
        uuid: wx.getStorageSync('uuid'),
        oldPass: that.getUserLoginPass()
      },
      success: function (res) {
        if (!res.statusCode) {
          return;
        }
        if (res.data.result == 0) {
          wx.setStorageSync('pass', res.data.data.pass);
          wx.setStorageSync('temp', res.data.data.temp);
          wx.setStorageSync('ltime', res.data.data.ltime);
          that.globalData.loginData = res.data.data;
        } else {
          if (that.globalData._that && that.globalData._that.pageName == 'index') {
            that.globalData._that.setData({
              phoneAuthStatus: true,
              phoneAuthBtt: ''
            });
          } else {
            wx.navigateTo({
              url: '../login/login',
            });
          }
        }
      }
    })
  },
  /**
   * 返回值说明处理
   */
  getResultDesc: function (desc) {
    if (desc == null || desc == undefined || desc == '') {
      return '网络异常'
    }
    return desc
  },

  /**
   * 发送日志到服务器
   */
  sendLog: function () {
    // this.lajax.sendLog();
  },

  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function (code, name) {
    let title = encodeURIComponent('e家康护')
    let adPath = encodeURIComponent(this.globalData.mpWebUrl)
    wx.navigateTo({
      url: '/pages/index/webView/webView?title=' + title + '&adPath=' + adPath,
      success(res) {
        if (code == -200003) {
          util.mp_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -220003, name, 'open-success')
        } else {
          util.mp_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, code, name, 'open-success')
        }
      },
      fail(error) {
        if (code == -200003) {
          util.mp_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -210003, name, 'open-fail')
        } else {
          util.mp_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, code, name, 'open-fail')
        }
      }
    })
  },

  contacted() { // mark: 进入客服咨询 
    const baseVer = wx.getSystemInfoSync().SDKVersion
    let rst = commonUtil.compareVersion(baseVer, '2.19.0') // mark: 客服接入
    if (rst >= 0) {
      wx.openCustomerServiceChat({
        extInfo: {
          url: 'https://work.weixin.qq.com/kfid/kfced14b7ce957b5acb'
        },
        corpId: 'wwd11a8d1fbe4cdae3',
        success(res) {
          console.log("接入企业微信客服:", res)
        },
        fail: function (err) {
          console.error("接入企业微信客服:", err);
          wx.navigateTo({
            url: '/pages/callCenter/callCenter',
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/callCenter/callCenter',
      })
    }
  },

  /**
   * 记录关注公众号展示日志
   */
  recordShowMpLog: function (code, name) {
    util.mp_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, code, name, 'show')
  },

  /**
   * 全局关闭加载对话框函数，解决wx.hideLoading报错
   */
  hideLoading() {
    wx.hideLoading({
      success: (res) => {},
      fail: (error) => {},
    })
  },

})